package com.rest.demo.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Administrator
 * @decription
 * @Date 2018-02-07 9:25
 */
public class ChannelDemo {

    public static void main(String[] args) throws IOException {
        RandomAccessFile file = new RandomAccessFile("F:\\a.txt","rw");
        FileChannel channel = file.getChannel();

        //创建一个容量为48bytes的缓存区
        ByteBuffer buf = ByteBuffer.allocate(48);
        int bytesRead = -1;
        //将通道中的数据写入到缓存区中
        while((bytesRead = channel.read(buf)) != -1) {
            //将缓存写模式改成读模式
            buf.flip();
            byte[] bytes = new byte[1024];
            int i = 0;
            //读取数据并打印
            while (buf.hasRemaining()) {
                bytes[i++] = buf.get();
            }
            System.out.println(new String(bytes,0,bytesRead));
            buf.clear();
        }
        file.close();
    }
}
